package org.jeecg.modules.demo.crm.email;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class EmailUtils {

    public static String getHtmlContent(String subject, String content) {
        // 使用 InputStream 和 InputStreamReader 读取模板文件内容，并显式指定 UTF-8 编码
       try {
           Resource resource = new ClassPathResource("templates/email-template.html");
           try (InputStream inputStream = resource.getInputStream();
                InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader bufferedReader = new BufferedReader(reader)) {

               StringBuilder template = new StringBuilder();
               String line;
               while ((line = bufferedReader.readLine()) != null) {
                   template.append(line);
               }

               // 替换占位符
               return template.toString()
                       .replace("${subject}", subject) // 对主题进行编码
                       .replace("${content}", content); // 对内容进行编码
           }
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

    }

    public static File downloadFile(String fileUrl)  {
        try {
            URL url = new URL(fileUrl);
            String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
            File tempFile = File.createTempFile("attachment", fileName.substring(fileName.lastIndexOf('.')));
            try (InputStream in = url.openStream();
                 OutputStream out = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
            return tempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
